﻿using System;
using System.Net.Sockets;
using System.Threading.Tasks;
using NModbus;

namespace ModbusExample
{
    class Program
    {
        static async Task Main(string[] args)
        {
            try
            {
                // 创建TCP客户端连接
                using TcpClient client = new TcpClient("192.168.1.100", 502);

                // 创建Modbus TCP主站
                IModbusFactory factory = new ModbusFactory();
                IModbusMaster master = factory.CreateMaster(client);

                // 设置超时时间
                client.ReceiveTimeout = 1000;
                client.SendTimeout = 1000;

                // 从站地址
                byte slaveId = 1;

                // 读取保持寄存器示例 (地址0，长度10)
                ushort startAddress = 0;
                ushort numRegisters = 10;
                ushort[] registers = await master.ReadHoldingRegistersAsync(slaveId, startAddress, numRegisters);

                Console.WriteLine("读取保持寄存器结果:");
                for (int i = 0; i < registers.Length; i++)
                {
                    Console.WriteLine($"寄存器 {startAddress + i}: {registers[i]}");
                }

                // 写入单个寄存器示例
                ushort writeAddress = 10;
                ushort value = 1234;
                await master.WriteSingleRegisterAsync(slaveId, writeAddress, value);
                Console.WriteLine($"已写入值 {value} 到寄存器 {writeAddress}");

                // 读取线圈状态示例
                bool[] coils = await master.ReadCoilsAsync(slaveId, 0, 5);
                Console.WriteLine("读取线圈状态结果:");
                for (int i = 0; i < coils.Length; i++)
                {
                    Console.WriteLine($"线圈 {i}: {(coils[i] ? "ON" : "OFF")}");
                }

                // 写入单个线圈示例
                await master.WriteSingleCoilAsync(slaveId, 0, true);
                Console.WriteLine("已将线圈0设置为ON");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Modbus通信错误: {ex.Message}");
            }

            Console.WriteLine("按任意键退出...");
            Console.ReadKey();
        }
    }
}
